package com.fragrance.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.iot.model.v20170420.QueryDeviceByNameResponse.DeviceInfo;
import com.fragrance.cfg.FragranceJFinalCfg;
import com.fragrance.model.DeviceMainModel;
import com.fragrance.model.UserDeviceBindModel;
import com.fragrance.model.UserDeviceModel;
import com.fragrance.service.DeviceMainService;
import com.fragrance.service.IotApiService;
import com.fragrance.util.Constants;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

public class DeviceMainServiceImpl implements DeviceMainService {

	private Logger logger = LoggerFactory.getLogger(DeviceMainServiceImpl.class);

	private IotApiService iotApiService = new IotApiServiceImpl();

	/**
	 * 设备列表
	 */
	@Override
	public Map<String, Object> deviceList(Map<String, Object> params) {
		logger.info("-- begin DeviceServiceImpl.deviceList,params{}", params);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String simNo = params.get("simNo") == null ? "" : params.get("simNo").toString();
			String IMEI = params.get("IMEI") == null ? "" : params.get("IMEI").toString();
			String deviceStatus = params.get("deviceStatus") == null ? "" : params.get("deviceStatus").toString();
			String rightStatus = params.get("rightStatus") == null ? "" : params.get("rightStatus").toString();
			String pageNum = params.get("pageNum") == null ? "1" : params.get("pageNum").toString();
			String pageSize = params.get("pageSize") == null ? "20" : params.get("pageSize").toString();
			StringBuffer sql = new StringBuffer("FROM t_device_main where 1 = 1");
			if (!StringUtils.isBlank(simNo)) {
				sql.append(" and sim_no like '%" + simNo + "%'");
			}
			if (!StringUtils.isBlank(IMEI)) {
				sql.append(" and imei like '%" + IMEI + "%'");
			}
			if (!StringUtils.isBlank(deviceStatus)) {
				sql.append(" and device_status = '" + deviceStatus + "'");
			}
			if (!StringUtils.isBlank(rightStatus)) {
				sql.append(" and right_status = '" + rightStatus + "'");
			}
			Page<DeviceMainModel> devicePage = DeviceMainModel.me.paginate(Integer.parseInt(pageNum),
					Integer.parseInt(pageSize), "SELECT *", sql.toString());
			Map<String, Object> devicePageMap = new HashMap<String, Object>();
			devicePageMap.put("deviceList", devicePage.getList());
			devicePageMap.put("totalPage", devicePage.getTotalPage());
			devicePageMap.put("pageNum", devicePage.getPageNumber());
			devicePageMap.put("pageSize", devicePage.getPageSize());
			devicePageMap.put("totalRow", devicePage.getTotalRow());
			resultMap.put("code", Constants.SUCCESS_CODE);
			resultMap.put("msg", Constants.SUCCESS_MSG);
			resultMap.put("data", devicePageMap);
		} catch (Exception e) {
			logger.error("-- error DeviceServiceImpl.deviceList,Exception{}", e);
			resultMap.put("code", "200101");
			resultMap.put("msg", "获取设备列表失败");
		}
		logger.info("-- end DeviceServiceImpl.deviceList========");
		return resultMap;
	}

	@Override
	public Map<String, Object> deviceDetail(Map<String, Object> params) {
		logger.info("-- begin DeviceServiceImpl.deviceDetail,params{}", params);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String deviceId = params.get("deviceId") == null ? "" : params.get("deviceId").toString();
			logger.info("-- in DeviceServiceImpl.deviceDelete,deviceId=={}", deviceId);
			DeviceMainModel deviceDetail = DeviceMainModel.me.findById(deviceId);
			logger.info("-- in DeviceServiceImpl.deviceDelete,deviceDetail{}", deviceDetail);
			Map<String, Object> deviceMap = new HashMap<String, Object>();
			deviceMap.put("deviceDetail", deviceDetail);
			resultMap.put("code", Constants.SUCCESS_CODE);
			resultMap.put("msg", Constants.SUCCESS_MSG);
			resultMap.put("data", deviceMap);
		} catch (Exception e) {
			logger.error("-- error DeviceServiceImpl.deviceDetail,Exception{}", e);
			resultMap.put("code", "200201");
			resultMap.put("msg", "获取设备详情失败");
		}
		logger.info("-- end DeviceServiceImpl.deviceDetail======");
		return resultMap;
	}

	@Override
	public Map<String, Object> deviceDelete(Map<String, Object> params) {
		logger.info("-- begin DeviceServiceImpl.deviceDelete,params{}", params);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String deviceId = params.get("deviceId") == null ? "" : params.get("deviceId").toString();
			boolean flag = DeviceMainModel.me.deleteById(deviceId);
			resultMap.put("code", Constants.SUCCESS_CODE);
			resultMap.put("msg", Constants.SUCCESS_MSG);
		} catch (Exception e) {
			logger.error("-- error DeviceServiceImpl.deviceDelete,Exception{}", e);
			resultMap.put("code", "200301");
			resultMap.put("msg", "删除设备失败");
		}
		logger.info("-- end DeviceServiceImpl.deviceDelete======");
		return resultMap;
	}

	@Override
	public Map<String, Object> deviceAdd(Map<String, Object> params) {
		logger.info("-- begin DeviceServiceImpl.deviceAdd,params{}", params);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String simNo = params.get("simNo") == null ? "" : params.get("simNo").toString();
			String IMEI = params.get("IMEI") == null ? "" : params.get("IMEI").toString();
			String deviceStatus = params.get("deviceStatus") == null ? "" : params.get("deviceStatus").toString();
			String rightStatus = params.get("rightStatus") == null ? "" : params.get("rightStatus").toString();
			String location = params.get("location") == null ? "" : params.get("location").toString();
			String userId = params.get("userId") == null ? "" : params.get("userId").toString();
			boolean flag = new DeviceMainModel().set("sim_no", simNo).set("imei", IMEI)
					.set("device_status", deviceStatus).set("right_status", rightStatus).set("location", location)
					.set("create_id", userId).set("create_date", new Date()).save();
			resultMap.put("code", Constants.SUCCESS_CODE);
			resultMap.put("msg", Constants.SUCCESS_MSG);
		} catch (Exception e) {
			logger.error("-- error DeviceServiceImpl.deviceAdd,Exception{}", e);
			resultMap.put("code", "200401");
			resultMap.put("msg", "添加设备失败");
		}
		logger.info("-- end DeviceServiceImpl.deviceAdd=======");
		return resultMap;
	}

	@Override
	public Map<String, Object> deviceEdit(Map<String, Object> params) {
		logger.info("-- begin DeviceServiceImpl.deviceEdit,params{}", params);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String deviceId = params.get("deviceId") == null ? "" : params.get("deviceId").toString();
			String simNo = params.get("simNo") == null ? "" : params.get("simNo").toString();
			String IMEI = params.get("IMEI") == null ? "" : params.get("IMEI").toString();
			String deviceStatus = params.get("deviceStatus") == null ? "" : params.get("deviceStatus").toString();
			String rightStatus = params.get("rightStatus") == null ? "" : params.get("rightStatus").toString();
			String location = params.get("location") == null ? "" : params.get("location").toString();
			String userId = params.get("userId") == null ? "" : params.get("userId").toString();
			boolean flag = DeviceMainModel.me.findById(deviceId).set("sim_no", simNo).set("imei", IMEI)
					.set("device_status", deviceStatus).set("right_status", rightStatus).set("location", location)
					.set("update_id", userId).set("update_date", new Date()).update();
			resultMap.put("code", Constants.SUCCESS_CODE);
			resultMap.put("msg", Constants.SUCCESS_MSG);
		} catch (Exception e) {
			logger.error("-- error DeviceServiceImpl.deviceEdit,Exception{}", e);
			resultMap.put("code", "200501");
			resultMap.put("msg", "编辑设备失败");
		}
		logger.info("-- end DeviceServiceImpl.deviceEdit=======");
		return resultMap;
	}

	@Override
	public Map<String, Object> deviceWorkList(Map<String, Object> params) {
		logger.info("-- begin DeviceServiceImpl.deviceWorkList,params{}", params);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String simNo = params.get("simNo") == null ? "" : params.get("simNo").toString();
			String IMEI = params.get("IMEI") == null ? "" : params.get("IMEI").toString();
			String pageNum = params.get("pageNum") == null ? "1" : params.get("pageNum").toString();
			String pageSize = params.get("pageSize") == null ? "20" : params.get("pageSize").toString();

			StringBuffer sql = new StringBuffer(
					"FROM t_user_device d inner join t_wx_user u on d.wx_open_id = u.wx_open_id where d.status = 'N'");
			if (!StringUtils.isBlank(simNo)) {
				sql.append(" and d.sim_no like '%" + simNo + "%'");
			}
			if (!StringUtils.isBlank(IMEI)) {
				sql.append(" and d.imei like '%" + IMEI + "%'");
			}
			Page<UserDeviceModel> workDevicePage = UserDeviceModel.me.paginate(Integer.parseInt(pageNum),
					Integer.parseInt(pageSize), "SELECT *,u.nick_name", sql.toString());
			Map<String, Object> workDevicePageMap = new HashMap<String, Object>();
			workDevicePageMap.put("workDeviceList", workDevicePage.getList());
			workDevicePageMap.put("totalPage", workDevicePage.getTotalPage());
			workDevicePageMap.put("pageNum", workDevicePage.getPageNumber());
			workDevicePageMap.put("pageSize", workDevicePage.getPageSize());
			workDevicePageMap.put("totalRow", workDevicePage.getTotalRow());
			resultMap.put("code", Constants.SUCCESS_CODE);
			resultMap.put("msg", Constants.SUCCESS_MSG);
			resultMap.put("data", workDevicePageMap);
		} catch (Exception e) {
			logger.error("-- error DeviceServiceImpl.deviceWorkList,Exception{}", e);
			resultMap.put("code", "200601");
			resultMap.put("msg", "获取工作设备列表失败");
		}
		logger.info("-- end DeviceServiceImpl.deviceWorkList======");
		return resultMap;
	}

	/**
	 * 前缀
	 */
	public final static String PREFIX = "DY";

	/**
	 * 0允许使用，1代表锁机状态
	 */
	public final static String AUTH_0 = "0";

	/**
	 * 0允许使用，1代表锁机状态
	 */
	public final static String AUTH_1 = "1";

	/**
	 * 0代表开机，1代表关机状态
	 */
	public final static String OPEN = "0";

	/**
	 * 0代表开机，1代表关机状态
	 */
	public final static String SHUTDOWN = "1";

	@Override
	public Map<String, Object> deviceOprate(Map<String, Object> params) {
		logger.info("-- begin DeviceServiceImpl.deviceOprate,params{}", params);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String deviceId = params.get("deviceId") == null ? "" : params.get("deviceId").toString();
			String IMEI = params.get("IMEI") == null ? "" : params.get("IMEI").toString();
			String rightStatus = params.get("rightStatus") == null ? "" : params.get("rightStatus").toString();

			// 1、获取香氛机信息t_device_main
			List<DeviceMainModel> deviceMainModels = DeviceMainModel.me.findDeviceByImei(IMEI);
			if (deviceMainModels == null || deviceMainModels.size() == 0) {
				logger.info("根据imei=" + IMEI + "获取不到设备信息");
				resultMap.put("code", Constants.PARAM_VAILD_CODE);
				resultMap.put("msg", Constants.PARAM_VAILD_MSG);
				return resultMap;
			}

			/*
			 * //更新设备状态 boolean flag =
			 * DeviceMainModel.me.findById(deviceId).set("right_status",
			 * rightStatus) .set("device_status", rightStatus) .update();
			 */

			// iotcfg.properties配置的productKey
			String productKey = FragranceJFinalCfg.iotcfgProp.get("carla.iot.productKey");
			if (StringUtils.isEmpty(productKey)) {
				logger.info("productKey请在iotcfg.properties配置");
				resultMap.put("code", Constants.PARAM_VAILD_CODE);
				resultMap.put("msg", Constants.PARAM_VAILD_MSG);
				return resultMap;
			}

			// 2、在云端获取机器状态是否在线
			DeviceMainModel deviceMainModel = deviceMainModels.get(0);
			String deviceName = deviceMainModel.getStr("imei");
			logger.info("productKey=" + productKey + ", deviceName=" + deviceName);
			DeviceInfo deviceInfo = iotApiService.queryDeviceByName(productKey, deviceName);
			if (deviceInfo != null && Constants.DEV_ONLINE.equals(deviceInfo.getDeviceStatus())) {
				// 进行远程关机操作
				logger.info("进行关机操作:" + JSON.toJSONString(deviceInfo));
				// 更新设备状态
				boolean flag = DeviceMainModel.me.findById(deviceId).set("right_status", rightStatus)
						.set("device_status", rightStatus).update();
				// 组装发送数据 TODO
				String openMsg = PREFIX + "4" + rightStatus;
				logger.info("发送给设备的数据++" + openMsg);
				String topic = "/" + productKey + "/" + deviceName + "/get";
				// 该数据发送为异步发送，所以前端需要轮询
				String publishResult = iotApiService.publishMssage(productKey, topic, openMsg);
				if (StringUtils.isEmpty(publishResult)) {
					logger.info("--锁机失败1--");
					resultMap.put("code", Constants.ERROR_CODE);
					resultMap.put("msg", Constants.ERROR_MSG);
					return resultMap;
				} else {
					logger.info("--锁机成功1--");
					// 查看当前设备是否开机中
					List<UserDeviceModel> deviceModels = UserDeviceModel.me
							.find("select * from t_user_device where imei = ? and device_status = 0", IMEI);
					if (null != deviceModels && deviceModels.size() == 1) {
						String closeTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()).toString();
						boolean flag1 = deviceModels.get(0).set("device_status", rightStatus)
								.set("close_time", closeTime).update();
						if (flag1) {
							logger.info("--锁机成功2--");
							resultMap.put("code", Constants.SUCCESS_CODE);
							resultMap.put("msg", Constants.SUCCESS_MSG);
						} else {
							logger.info("--锁机失败2--");
							resultMap.put("code", Constants.ERROR_CODE);
							resultMap.put("msg", Constants.ERROR_MSG);
						}
					} else {
						logger.info("--锁机成功3--");
						resultMap.put("code", Constants.SUCCESS_CODE);
						resultMap.put("msg", Constants.SUCCESS_MSG);
					}
				}
			}

		} catch (Exception e) {
			logger.error("-- error DeviceServiceImpl.deviceOprate,Exception{}", e);
			resultMap.put("code", "200701");
			resultMap.put("msg", "锁定设备失败");
		}
		logger.info("-- end DeviceServiceImpl.deviceOprate====");
		return resultMap;
	}

	@Override
	public Map<String, Object> checkBindAndOpen(Map<String, Object> params) {
		logger.info("-- begin DeviceServiceImpl.deviceCheck  params : ", params);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String imei = (String) params.get("imei");
		String openid = (String) params.get("openid");
		try {
			// 1、根据imei查找设备，如果该设备存在，并没有被锁机说明可用
			List<DeviceMainModel> deviceMainList = DeviceMainModel.me.checkDevice(imei, Constants.OPEN_STATUS);
			if (deviceMainList == null || deviceMainList.size() == 0) {
				resultMap.put("code", Constants.DEVICE_EXIST_CODE);
				resultMap.put("msg", Constants.DEVICE_EXIST_MSG);
				return resultMap;
			}
			DeviceMainModel deviceMainModel = deviceMainList.get(0);
			String status = deviceMainModel.getStr("device_status");
			if (Constants.OPEN_STATUS.equals(status)) {
				// 说明已经该机器已经开机
				// 1、确定开机的用户是不是该用户
				UserDeviceModel userDeviceModel = UserDeviceModel.me.findUserDevice(imei, Constants.OPEN_STATUS);
				if (userDeviceModel != null) {
					String wx_open_id = userDeviceModel.getStr("wx_open_id");
					if (openid.equals(wx_open_id)) {
						// 说明开机的是该用户，同时设备绑定了该用户  小程序需要处理
						resultMap.put("code", Constants.SUCCESS_CODE);
						resultMap.put("msg", Constants.SUCCESS_MSG);
						return resultMap;
					} else {
						// 说明开机的不是该用户  也即是绑定了设备的不是该用户  小程序需要处理
						logger.info("open：开机用户openid1 = " + wx_open_id + ", 我openid = " + openid);
						resultMap.put("code", Constants.OTHER_USER_BIND_AND_OPEN_CODE);
						resultMap.put("msg", Constants.OTHER_USER_BIND_AND_OPEN_MSG);
						return resultMap;
					}
				} else {
					logger.info("没有查询到任何开机记录");
					resultMap.put("code", Constants.NO_OPEN_RECORD_CODE);
					resultMap.put("msg", Constants.NO_OPEN_RECORD_MSG);
					return resultMap;
				}
			} else {
				//获取remark值，1代表改设备可以帮定多个用户，2代表该设备智能绑定一个用户
				String remark1 = deviceMainModel.getStr("remark1");
				// 说明该机器没有开机
				// 2、查看该用户是否绑定了该设备
				List<UserDeviceBindModel> userDeviceBindModelList = UserDeviceBindModel.me.findBindDevice(imei);
				if(remark1.equals("1")){
					String wx_open_id = "";
					if(userDeviceBindModelList != null && userDeviceBindModelList.size() <= 5){
						for(int i = 0; i <userDeviceBindModelList.size();i++){
							UserDeviceBindModel userDeviceBindInfo = userDeviceBindModelList.get(i);
							wx_open_id = userDeviceBindInfo.get("wx_open_id");
							if(openid.equals(wx_open_id)){
								//说明该机器没有开机绑定的该用户   小程序需要处理
								logger.info("说明该机器没有开机，同时绑定的该用户");
								resultMap.put("code", Constants.BIND_NO_OPEN_CODE);
								resultMap.put("msg", Constants.BIND_NO_OPEN_MSG);
								return resultMap;
							}else{
								logger.info("说明该机器没有开机也没有达到绑定用户最大值");
								resultMap.put("code", Constants.NO_BIND_NO_OPEN_CODE);
								resultMap.put("msg", Constants.NO_BIND_NO_OPEN_MSG);
								return resultMap;
								
							}
						}
					}else{
						// 说明绑定了设备的不是该用户 小程序需要处理
						logger.info("cose：开机用户openid2 = " + wx_open_id + ", 我openid = " + openid);
						resultMap.put("code", Constants.OTHER_USER_BIND_NO_OPEN_CODE);
						resultMap.put("msg", Constants.OTHER_USER_BIND_NO_OPEN_MSG);
						return resultMap;
					}
				}else if(remark1.equals("2")){
					if(userDeviceBindModelList != null && userDeviceBindModelList.size() > 0){
						UserDeviceBindModel userDeviceBindModel = userDeviceBindModelList.get(0);
						String wx_open_id = userDeviceBindModel.get("wx_open_id");
						if(openid.equals(wx_open_id)){
							//说明该机器没有开机绑定的该用户   小程序需要处理
							logger.info("说明该机器没有开机，同时绑定的该用户");
							resultMap.put("code", Constants.BIND_NO_OPEN_CODE);
							resultMap.put("msg", Constants.BIND_NO_OPEN_MSG);
							return resultMap;
						}else{
							// 说明绑定了设备的不是该用户 小程序需要处理
							logger.info("cose：开机用户openid3 = " + wx_open_id + ", 我openid = " + openid);
							resultMap.put("code", Constants.OTHER_USER_BIND_NO_OPEN_CODE);
							resultMap.put("msg", Constants.OTHER_USER_BIND_NO_OPEN_MSG);
							return resultMap;
						}
					}else{
						//说明该机器没有开机也没有绑定任何用户   小程序需要处理
						logger.info("说明该机器没有开机也没有绑定任何用户");
						resultMap.put("code", Constants.NO_BIND_NO_OPEN_CODE);
						resultMap.put("msg", Constants.NO_BIND_NO_OPEN_MSG);
						return resultMap;
					}
				}
			}
		} catch (Exception e) {
			logger.error("--error DeviceServiceImpl.deviceCheck查找设备异常", e);
			resultMap.put("code", "100010");
			resultMap.put("msg", "查询设备异常");
		}
		return resultMap;
	}

	public List<DeviceMainModel> findDevice(String imei) {
		return DeviceMainModel.me.findDevice(imei);
	}

	public UserDeviceModel isOpen(String imei) {
		return UserDeviceModel.me.isOpen(imei);
	}

	public UserDeviceModel isUse(String imei, String openid) {
		return UserDeviceModel.me.isUse(imei, openid);
	}

	public boolean addUserDevice(Map<String, String> data) {
		return UserDeviceModel.me.addUserDevice(data);
	}

	public UserDeviceModel findUserDevice(String imei, String openId, String deviceStatus) {
		return UserDeviceModel.me.findUserDevice(imei, openId, deviceStatus);
	}

	public boolean updateUserDevice(Map<String, String> data) {
		return UserDeviceModel.me.updateUserDevice(data);
	}

	// 设备更新档位
	public boolean updateUserDeviceGear(Map<String, Object> data) {
		return UserDeviceModel.me.updateUserDeviceGear(data);
	}

	@Override
	public Map<String, Object> addDeviceByExcel(Map<String, Object> params) {
		logger.info("-- begin DeviceServiceImpl.deviceCheck  params{}", params);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<List<String[]>> deviceList = params.get("list") == null ? null : (List<List<String[]>>) params.get("list");
		String userId = params.get("userId") == null ? "" : params.get("userId").toString();
		List<DeviceMainModel> deviceModelList = new ArrayList<DeviceMainModel>();
		try {
			if (deviceList != null && deviceList.size() > 0) {
				StringBuffer simNoErrStr = new StringBuffer();// sim卡号 1
				StringBuffer isSimNoErrStr = new StringBuffer();// sim卡号 是否已存在
				StringBuffer IMEIErrStr = new StringBuffer();// imei号 2
				StringBuffer isIMEIErrStr = new StringBuffer();// imei号 是否已存在
				StringBuffer deviceStatusErrStr = new StringBuffer();// 设备状态
																		// 开机和关机
																		// 3
				StringBuffer rightStatusErrStr = new StringBuffer();// 设备权限
																	// 锁机和允许使用 4
				StringBuffer locationErrStr = new StringBuffer(); // 设备地址 5

				List<String> simList = new ArrayList<String>();
				List<String> imeiList = new ArrayList<String>();

				try {
					// 遍历上传的表行数
					for (List<String[]> sheetList : deviceList) { // sheet
						if (sheetList == null) {
							continue;
						}
						// 遍历每一行的数组集合
						for (int i = 0; i < sheetList.size(); i++) {
							String[] rowList = sheetList.get(i);
							String[] values = rowList;

							logger.debug(" -- 解析excle的第" + (i + 1) + "行数据为  =========== " + Arrays.toString(values));
							if (values == null || values.length <= 0) {
								continue;
							}
							// sim卡号 1
							if (StringUtils.isBlank(values[1])) {
								simNoErrStr.append(values[values.length - 1] + "-2,");
							}
							// imei号 2
							if (StringUtils.isBlank(values[2])) {
								IMEIErrStr.append(values[values.length - 1] + "-3,");
							}
							// 设备状态 开机和关机 3
							if (StringUtils.isBlank(values[3])) {
								deviceStatusErrStr.append(values[values.length - 1] + "-4,");
							}
							// 设备权限 锁机和允许使用 4
							if (StringUtils.isBlank(values[4])) {
								rightStatusErrStr.append(values[values.length - 1] + "-5,");
							}
							// 设备地址 5
							if (StringUtils.isBlank(values[5])) {
								locationErrStr.append(values[values.length - 1] + "-6,");
							}
							// 判断sim号是否已存在
							if (!StringUtils.isBlank(values[1].trim())
									&& DeviceMainModel.me.deviceIsExist(values[1].trim(), "")) {
								isSimNoErrStr.append(values[values.length - 1] + "-2,");// sim号是否已存在
							}

							// 判断imei号是否已存在
							if (!StringUtils.isBlank(values[2].trim())
									&& DeviceMainModel.me.deviceIsExist("", values[2].trim())) {
								isIMEIErrStr.append(values[values.length - 1] + "-3,");// imei号是否已存在
							}

							DeviceMainModel deviceInfo = new DeviceMainModel();
							deviceInfo.set("sim_no", values[1].replaceAll("\r\n|\r|\n", "").trim());
							deviceInfo.set("IMEI", values[2].replaceAll("\r\n|\r|\n", "").trim());
							deviceInfo.set("device_status", values[3].replaceAll("\r\n|\r|\n", "").trim());
							deviceInfo.set("right_status", values[4].replaceAll("\r\n|\r|\n", "").trim());
							deviceInfo.set("location", values[5].replaceAll("\r\n|\r|\n", "").trim());
							deviceInfo.set("create_id", userId);
							deviceInfo.set("create_date", new Date());

							simList.add(values[1].replaceAll("\r\n|\r|\n", "").trim());// 门店名称
							imeiList.add(values[2].replaceAll("\r\n|\r|\n", "").trim());// 账号列表

							deviceModelList.add(deviceInfo);
						}
					}
				} catch (Exception e1) {
					logger.error("-- error EXCEL解析错误 --4015200409-- EXCEL解析错误 -- 异常信息", e1);
					resultMap.put("code", "4015200409");
					resultMap.put("msg", "EXCEL格式不正确");
					return resultMap;
				}

				// 判断Excle表格中是否有重复的登录账号
				if (isRepeatStr(simList)) {
					resultMap.put("code", "4015200410");
					resultMap.put("msg", "EXCEL中有重复的sim号");
					return resultMap;
				}

				// 判断Excle表格中是否有重复的门店名称
				if (isRepeatStr(imeiList)) {
					resultMap.put("code", "4015200411");
					resultMap.put("msg", "EXCEL中有重复的imei号");
					return resultMap;
				}

				StringBuffer sb = new StringBuffer();
				if (simNoErrStr.length() > 0) {
					sb.append(simNoErrStr.substring(0, simNoErrStr.length() - 1).toString() + "行sim号不能为空,");
				}
				if (IMEIErrStr.length() > 0) {
					sb.append(IMEIErrStr.substring(0, IMEIErrStr.length() - 1).toString() + "行imei号不能为空,");
				}
				if (deviceStatusErrStr.length() > 0) {
					sb.append(
							deviceStatusErrStr.substring(0, deviceStatusErrStr.length() - 1).toString() + "行设备状态不能为空,");
				}
				if (rightStatusErrStr.length() > 0) {
					sb.append(
							rightStatusErrStr.substring(0, rightStatusErrStr.length() - 1).toString() + "行设备权限状态不能为空,");
				}
				if (locationErrStr.length() > 0) {
					sb.append(locationErrStr.substring(0, locationErrStr.length() - 1).toString() + "行设备地址不能为空,");
				}
				if (isSimNoErrStr.length() > 0) {
					sb.append(isSimNoErrStr.substring(0, isSimNoErrStr.length() - 1).toString() + "行sim号已存在,");
				}
				if (isIMEIErrStr.length() > 0) {
					sb.append(isIMEIErrStr.substring(0, isIMEIErrStr.length() - 1).toString() + "行imei号已存在,");
				}

				if (sb.length() > 0) {
					resultMap.put("code", "4015200412");
					resultMap.put("msg", sb.append("请修改对应错误的地方！").toString());
					return resultMap;
				}
				if (deviceModelList == null || deviceModelList.size() <= 0) {
					logger.info("-- 新增的设备信息为空 -- deviceInfoList：" + deviceModelList);
					resultMap.put("code", "4015200413");
					resultMap.put("msg", "上传的excle设备信息为空");
					return resultMap;
				}
			}

			if (deviceModelList != null && deviceModelList.size() > 0) {
				String sql = "insert into t_device_main(sim_no,imei,device_status,right_status,location,create_date,create_id,status) values(?,?,?,?,?,?,?,?)";
				int[] result = Db.batch(sql,
						"sim_no,imei,device_status,right_status,location,create_date,create_id,status", deviceModelList,
						100);
			}
			resultMap.put("code", Constants.SUCCESS_CODE);
			resultMap.put("msg", Constants.SUCCESS_MSG);
			return resultMap;
		} catch (Exception e) {
			logger.error("--error DeviceServiceImpl.addDeviceByExcel批量新增设备异常异常", e);
			resultMap.put("code", "100010");
			resultMap.put("msg", "批量新增设备异常异常");
			return resultMap;
		}
	}

	@Override
	public boolean updateStatus(Integer newDeviceStatus, String imei, Integer oldDeviceStatus) {
		return DeviceMainModel.me.updateStatus(newDeviceStatus, imei, oldDeviceStatus);
	}

	/**
	 * 是否有重复的号
	 * 
	 * @param list
	 * @return
	 */
	private boolean isRepeatStr(List<String> list) {
		String temp = "";
		for (int i = 0; i < list.size() - 1; i++) {
			temp = list.get(i);
			for (int j = i + 1; j < list.size(); j++) {
				if (temp.equals(list.get(j))) {
					logger.info("第" + (i + 1) + "个跟第" + (j + 1) + "个重复，值是：" + temp);
					return true;
				}
			}
		}
		return false;
	}

	// 查询开机设备信息
	public UserDeviceModel deviceOpenInfo(Map<String, Object> data) {
		return UserDeviceModel.me.deviceOpenInfo(data);
	}

	// 获取在线开机列表
	public List<UserDeviceModel> getDeviceWorkList(String openid) {
		return UserDeviceModel.me.getDeviceWorkList(openid);
	}

	// 判断绑定设备是否开机
	public UserDeviceModel isBindOpenOpen(Map<String, Object> data) {
		return UserDeviceModel.me.isBindOpen(data);
	}

	//给设备开起多台绑定权限
	public Map<String, Object> deviceBindRight(Map<String, Object> params) {
		
		return DeviceMainModel.me.deviceBindRight(params);
	}

	//更新定时时间
	@Override
	public boolean updateWorkTime(Map<String, Object> timeResult) {
		// TODO Auto-generated method stub
		return UserDeviceModel.me.updateWorkTime(timeResult);
	}
	
	
	
}
